package com.shiro_02.contooler;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyControoler {

    @RequestMapping("/tologin")
    public String tologin(){
        return "login";
    }
     @GetMapping({"/index","/"})
    public String index(Model model){
         model.addAttribute("msg","你好");
         return "index";
     }

     @GetMapping("/user/add")
    public String add(){
         return "/user/add";
     }
    @GetMapping("/user/update")
    public String update(){
        return "/user/update";
    }

    @RequestMapping("/login")
    public String login(String username ,String password,Model model){
       //获取当前用户
        Subject subject = SecurityUtils.getSubject();
       //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);//执行登录的方法
              subject.getSession().setAttribute("user",username);
              return "/index";
        } catch (AuthenticationException e) {
            model.addAttribute("msg","身份验证异常");
            return "/login";
        }
    }

    @RequestMapping("/noatul")
    @ResponseBody
   public String uanth(){
        return "没有授权的页面!";
    }

    //注销
    @RequestMapping("/outlogin")
    public String out(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    return "index";
    }
}
